class Client < ActiveRecord::Base
  
  has_many :assistances, :dependent => :destroy
  has_many :contracts, :dependent => :destroy
  
  validates_format_of   :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates_presence_of :name, :if => :control_presence_of_name?
  validates_presence_of :surname, :if => :control_presence_of_surname?
  validates_presence_of :society, :if => :control_presence_of_name_surname?
  validates_presence_of :email
  validates_length_of   :tel_office, :maximum => 15, :unless => Proc.new { |t| t.tel_office.blank? || t.tel_office.nil? }
  validates_length_of   :tel_home, :maximum => 15, :unless => Proc.new { |t| t.tel_home.blank? || t.tel_home.nil? }
  validates_length_of   :tel_cell, :maximum => 15, :unless => Proc.new { |t| t.tel_cell.blank? || t.tel_cell.nil? }
  validates_length_of   :fax, :maximum => 15, :unless => Proc.new { |t| t.fax.blank? || t.fax.nil? }
  validates_length_of   :society, :maximum => 120, :unless => Proc.new { |t| t.society.blank? || t.society.nil? }
  validates_length_of   :email, :maximum => 120
  validates_length_of   :fiscal_code, :maximum => 20, :unless => Proc.new { |t| t.fiscal_code.blank? || t.fiscal_code.nil?}
  validates_length_of   :webpage, :maximum => 120, :unless => Proc.new { |t| t.webpage.blank? || t.webpage.nil? }
  validates_length_of   :address, :maximum => 120, :unless => Proc.new { |t| t.address.blank? || t.address.nil? }
  validates_length_of   :city, :maximum => 50, :unless => Proc.new { |t| t.city.blank? || t.city.nil? }
  validates_length_of   :PI, :maximum => 20, :unless => Proc.new { |t| t.PI.blank? || t.PI.nil? }
  validates_numericality_of :cap, :unless => Proc.new { |t| t.cap.blank? || t.cap.nil? }
  
  before_save :normalize
  
  def normalize
    name.capitalize!
    surname.capitalize!
  end
  
  def control_presence_of_name?
    !surname.blank? && society.blank?
  end
  
  def control_presence_of_surname?
    !name.blank? && society.blank?
  end

  def control_presence_of_name_surname?
    name.blank? && surname.blank?
  end

  def surname_name
    surname + " " + name    
  end
  
  def name_or_society
    unless control_presence_of_name_surname? || society.blank?
      society
    else
      surname_name
    end
  end
  
  def short_name
    surname + " " + name[0,1] + "."
  end
  
  def short_email
    length = email.size
    if length > 25
      pivot = length/2
      diff = (length - 22)/2
      email[0,pivot-diff] + "..." + email[pivot+diff, length]
    else
      email
    end
  end
  
end